# -*- coding:utf-8 -*-
import os
import sys
import requests
import datetime
from Crypto.Cipher import AES

def heBingTsVideo(download_path,hebing_path):
    all_ts = os.listdir(download_path)
    with open(hebing_path, 'wb+') as f:
        for i in range(len(all_ts)):
            ts_video_path = os.path.join(download_path, all_ts[i])
            f.write(open(ts_video_path, 'rb').read())
    print("合并完成！！")

if __name__ == '__main__':
    download_path = os.getcwd() + "/download"
    if not os.path.exists(download_path):
        os.mkdir(download_path)

    # 新建日期文件夹
    download_path = os.path.join(download_path, datetime.datetime.now().strftime('%Y%m%d_%H%M%S'))
    # print download_path
    os.mkdir(download_path)

    print(download_path)

    url = "https://lajiao-bo.com/20190505/3Howd2B5/index.m3u8"
    # url = "https://valipl.cp31.ott.cibntv.net/6975472841A3F71B0E168349A/05007C00006218EA5A8BB78000000040EEFA57-9690-40DD-A754-4FA9F1EEEE72_video.m3u8?ccode=0502&duration=2707&expire=18000&psid=fa96d748a673a8944cbe47f782dcfa4e43346&ups_client_netip=ddc68a48&ups_ts=1647247176&ups_userid=&apscid=&mnid=&umt=1&type=cmaf4hd&utid=XE%2B%2FGP23XDYCATwaNa571tjs&vid=XNTIwNTIxNTUyOA%3D%3D&s=deea28f98c604aa9acf8&sp=&t=20498bafc900dc3&cug=2&bc=2&si=5&eo=0&vkey=B96961f0fc1f681c4d92e6bd9c9f692fe"
    all_content = requests.get(url).text
    # print(all_content)

    splits = all_content.split("\n")
    web = url.split("com/")[0] + 'com'
    # web = url.split("net/")[0]+'net'

    m3u8s = {}

    for idx, line in enumerate(splits):
        if (line.startswith("#EXT-X-STREAM-INF")):
            fenbianlv = line.split(',')[-1].split('=')[-1]
            m3u8s[fenbianlv] = web + splits[idx + 1]

    max = 0
    max_url = ''
    for fenbianlv in m3u8s:
        kuan = fenbianlv.split('x')[0]
        if (int(max) < int(kuan)):
            max = kuan
            max_url = m3u8s[fenbianlv]

    print(max_url)

    all_content = requests.get(max_url).text
    # print(all_content)

    method = ''
    key_url = ''
    tss = []
    splits = all_content.split("\n")
    for idx, line in enumerate(splits):
        if (line.startswith("#EXT-X-KEY")):
            keymap = line.split(',')
            method = keymap[0].split(':')[-1].split('=')[-1]
            uri = keymap[1].split(':')[-1].split('=')[-1].replace('"', '')
            key_url = (web + uri)
        if (line.endswith("ts")):
            tss.append(web + line)

    print(method, key_url)

    key = requests.get(key_url).content

    print(key)
    base = 100000
    i = base

    for ts_url in tss:
        i = i + 1
        res = requests.get(ts_url)
        # print(res)
        # print(res.text)
        aes = AES.new(key, AES.MODE_CBC, key)  # 初始化加密器
        decrypted_text = aes.decrypt(res.content)  # 解密


        c_fule_name = str(i)

        with open(os.path.join(download_path, c_fule_name + ".ts"), 'ab') as f:
            f.write(decrypted_text)

        print("============", i-base, '/', len(tss), "============")

    heBingTsVideo(download_path,os.path.join(download_path, "index.mp4"))
    print("============end============")
